package com.iwinding.ladygg.receiver;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.iwinding.ladygg.AppForegroundStateManager;
import com.iwinding.ladygg.bluetooth.impblekit.BleKitManager;
import com.iwinding.ladygg.bluetooth.impblekit.ICaneBleApi;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.modle.bean.JpushSosBean;
import com.iwinding.ladygg.ui.act.SosDetailActivity;
import com.iwinding.ladygg.ui.view.SosDialogView;
import com.iwinding.ladygg.utils.GsonUtil;
import com.iwinding.ladygg.utils.HexStringUtil;
import com.iwinding.ladygg.utils.LogUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.inuker.bluetooth.library.Constants;

import org.json.JSONObject;

import java.util.UUID;

import cn.jpush.android.api.JPushInterface;

import static com.inuker.bluetooth.library.Constants.EXTRA_CHARACTER_UUID;
import static com.inuker.bluetooth.library.Constants.EXTRA_DESCRIPTOR_UUID;
import static com.inuker.bluetooth.library.Constants.EXTRA_MAC;
import static com.inuker.bluetooth.library.Constants.EXTRA_SERVICE_UUID;

/**
 * Created by hezhiyong on 2017/4/13.
 */

public class MyReceiver extends BroadcastReceiver {

    String REGISTRATION = "cn.jpush.android.intent.REGISTRATION";
    String REGISTRATION_OPENED = "cn.jpush.android.intent.NOTIFICATION_OPENED";//打开通知栏
    String NOTIFICATION_RECEIVED = "cn.jpush.android.intent.NOTIFICATION_RECEIVED";//打开通知栏

    String PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";

    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtil.i("@hzy", "-------" + intent.getAction());
        if (intent.getAction().equals(REGISTRATION)) {
            Bundle bundle = intent.getExtras();
            String jpushid = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            JPushInterface.setLatestNotificationNumber(context, 5);
            SPUtils.putSpProperty(context, SPConstant.JPUSHID, jpushid);
        } else if (intent.getAction().equals(REGISTRATION_OPENED)) {
            JPushInterface.clearLocalNotifications(context);
            Bundle bundle = intent.getExtras();
            String type = bundle.getString(JPushInterface.EXTRA_EXTRA);
            try {
                JSONObject jsonObject = new JSONObject(type);
                parseJson(context, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (intent.getAction().equals(NOTIFICATION_RECEIVED)) {
            Activity activity = AppForegroundStateManager.getInstance().getForegroundActivity();
            if (activity == null) {
                return;
            }
            JPushInterface.clearLocalNotifications(context);
            JPushInterface.clearAllNotifications(context);
            Bundle bundle = intent.getExtras();
            String type = bundle.getString(JPushInterface.EXTRA_EXTRA);
            try {
                JSONObject jsonObject = new JSONObject(type);
                parseJson(context, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (intent.getAction().equals(PAIRING_REQUEST)) {
            BluetoothDevice btDevice = null;  //创建一个蓝牙device对象
            btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            BleKitManager.getInstance().setPin(btDevice.getAddress());
        } else if (intent.getAction().equals(Constants.ACTION_CHARACTER_CHANGED)) {
            String mac = intent.getStringExtra(EXTRA_MAC);
            UUID service = (UUID) intent.getSerializableExtra(EXTRA_SERVICE_UUID);
            UUID character = (UUID) intent.getSerializableExtra(EXTRA_CHARACTER_UUID);
            UUID descriptor = (UUID) intent.getSerializableExtra(EXTRA_DESCRIPTOR_UUID);
            byte[] value = intent.getByteArrayExtra(Constants.EXTRA_BYTE_VALUE);
            LogUtil.i("@hzy", "-----------" + HexStringUtil.bytesToHexString(value));

            if(isHuawei7()){
                ICaneBleApi.getInstance().analysis(value);
            }
//            BleConnectManager.write(mac, service, character, value, null);
        }
    }

    boolean isHuawei7() {
        String sdk = android.os.Build.VERSION.SDK; // SDK号--24
        String manufacturer = android.os.Build.MANUFACTURER;//厂商--HUAWEI
        String model = android.os.Build.MODEL;// 手机型号--DLI-AL10
        String release = android.os.Build.VERSION.RELEASE; // android系统版本号--7.0
        String brand = android.os.Build.BRAND; // android系统版本号--HONOR
        int level = Util.getEmuiLeval();

        boolean is7 = TextUtils.equals(release, "7.0") || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
        boolean isHuawei = TextUtils.equals(manufacturer, "HUAWEI") || TextUtils.equals(brand, "HONOR") || level > 0;
        return is7 && isHuawei;
    }

    void parseJson(final Context mContext, JSONObject jsonObject) {
        final JpushSosBean jpushSosBean = GsonUtil.getInstance().formJson(jsonObject.toString(), JpushSosBean.class);
        final SosDialogView sosDialogView = new SosDialogView(mContext);
        sosDialogView.setIconUrl(jpushSosBean.headImg);
        sosDialogView.setSender(jpushSosBean.nickName);
        sosDialogView.setLocation(jpushSosBean.address);
        sosDialogView.setOnClick(new SosDialogView.OnClick() {
            @Override
            public void onClickLeft() {
                sosDialogView.hide();
            }

            @Override
            public void onClickRight(Context context) {
                Activity activity = AppForegroundStateManager.getInstance().getForegroundActivity();
                if (activity == null) {
                    return;
                }
                Intent detail = new Intent(context, SosDetailActivity.class);
                if (activity instanceof SosDetailActivity) {
                    activity.finish();
                }
                detail.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                detail.putExtra(SosDetailActivity.SOSID, String.valueOf(jpushSosBean.sosId));
                context.startActivity(detail);
                sosDialogView.hide();
            }
        });
        sosDialogView.show();
    }

//    {"android":
//        {"extras":
//            {"userId":1,"messagetype":"sos",
//                    "sosId":110,"headImg":"http://120.77.22.230:8080/omh/static/upload/head//a7fc8a63-f15a-404a-a1f0-a81798a42c4d.jpeg",
//                    "address":"水岸山城","nickName":"13825283393"
//            },"alert":"sos急救"
//        },
//        "ios":
//        {"sound":"happy.caf","extras":
//            {"userId":1,"messagetype":"sos","sosId":110,
//                    "headImg":"http://120.77.22.230:8080/omh/static/upload/head//a7fc8a63-f15a-404a-a1f0-a81798a42c4d.jpeg",
//                    "address":"水岸山城","nickName":"13825283393"
//            },"badge":"5","alert":"sos急救"
//        }
//    }
}
